﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Configuration;

namespace SHNOPData.common
{
    /// <summary>
    /// 管理数据库连接
    /// </summary>
    public sealed class ConnMng
    {
        private static ConnMng theInstance = new ConnMng();
        private SqlConnection[] conn_pool = new SqlConnection[50];  // 同时打开的连接，不超过50个

        public static void ReleaseConnection(SqlConnection conn)
        {
            conn.Close();
        }

        public static SqlConnection GetConnection()
        {
            SqlConnection rst = null;
            int wait_count = 20;
            try
            {
                while (rst == null && wait_count > 0)
                {
                    for (int i = 0; i < theInstance.conn_pool.Length; i++)
                    {
                        if (null == theInstance.conn_pool[i])
                        {
                            theInstance.conn_pool[i] =
                                new SqlConnection(ConfigurationManager.ConnectionStrings["SHNOPConnectionString"].ConnectionString);
                            rst = theInstance.conn_pool[i];
                            break;
                        }
                        else if (ConnectionState.Closed == theInstance.conn_pool[i].State)
                        {
                            rst = theInstance.conn_pool[i];
                            break;
                        }
                    }
                    if (rst == null)
                    {
                        Thread.Sleep(1000);
                        --wait_count;
                    }
                }
                rst.Open();
            }
            catch (Exception) 
            {
                rst = null;
                throw;
            }
            return rst;
        }
    }
}